package com.choudou5.solr.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.choudou5.solr.bean.SysDynamicBean;
import com.choudou5.solr.bean.common.PageResult;
import com.choudou5.solr.bean.common.SolrQueryParam;
import com.choudou5.solr.core.util.SolrHelper;
import com.choudou5.solr.framework.constants.SolrConsts;
import com.choudou5.solr.framework.constants.SysConsts;
import com.choudou5.solr.framework.holder.SessionContextHolder;
import com.choudou5.solr.service.DicExtWordsService;
import com.choudou5.solr.service.ServiceHelper;
import com.choudou5.solr.service.SysDynamicService;
import com.choudou5.solr.util.AssertUtil;
import com.choudou5.solr.util.DateUtil;
import com.choudou5.solr.util.LogDeBugUtil;
import com.choudou5.solr.util.SolrJUtil;
import com.choudou5.spider.service.SpiderService;
import org.apache.solr.core.SolrCore;
import org.wltea.analyzer.dic.Dictionary;

import java.util.*;

/**
 * @name：索引接口
 * @author：choudou5
 * @date：2018/8/5
 */
public class IndexApi {

    private final DicExtWordsService dicExtWordsService = ServiceHelper.singleton(DicExtWordsService.class);
    private final SearchApi searchApi = SearchApi.getInstance();

    private IndexApi() {
    }
    private static class SingletonHolder{
        private static IndexApi instance = new IndexApi();

    }

    /**
     * 获取单例
     * @return
     */
    public static IndexApi getInstance() {
        return SingletonHolder.instance;
    }

    protected final SysDynamicService sysDynamicService = ServiceHelper.singleton(SysDynamicService.class);



    /**
     * 添加QA数据
     * @param taskId
     * @param categoryId
     * @param index
     */
    public void addQAData(String taskId, String categoryId, Integer index){
        SolrCore solrCore = SolrHelper.getCore(ApiConfig.API_QA);
        AssertUtil.isNotNull(solrCore, "solr系统未初始化 qa");

        List<Map<String, String>> spiderData =  SpiderService.getCacheSpiderData(taskId);
        AssertUtil.isNotEmpty(spiderData, "系统内部异常，请联系管理员！");
        Map<String, String> inputMap = spiderData.get(index);

        String keywords = inputMap.get(SolrConsts.KEY_KEYWORDS);
        inputMap.remove(SolrConsts.KEY_KEYWORDS);
        inputMap.put("id", DateUtil.getIntMs() + "");
        inputMap.put("firstCategoryId", categoryId);
        inputMap.put("createTime", DateUtil.toSolrDate(new Date()));
        if(StrUtil.isNotBlank(keywords)){
            Set<String> dicWords = new HashSet<>();
            String[] wordArr = StrUtil.splitToArray(keywords, '|');
            for (String word : wordArr) {
                if(word.length() <= 4){
                    dicWords.add(word);
                }
            }
            if(CollUtil.isNotEmpty(dicWords)){
                //加载到词库
                Set<String> succWordList = Dictionary.getSingleton().addExtDict(dicWords);
                //加入到数据库
                if(!succWordList.isEmpty()){
                    LogDeBugUtil.debug(" 成功加入词库 " + succWordList.size() + "条");
                    dicExtWordsService.imporWords(succWordList);
                }
            }
        }
        //添加数据
        SolrJUtil.add(inputMap, solrCore);
    }

    public String reIndex(String module){
        LogDeBugUtil.debug(module + " 开始重建索引");
        SolrCore solrCore = SolrHelper.getCore(module);
        AssertUtil.isNotNull(solrCore, "solr系统未初始化 " + module);

        long begin = System.currentTimeMillis();
        SolrQueryParam queryParam = new SolrQueryParam(module, SolrJUtil.QUERY_ALL);
        int start = 0, rows = 200;
        queryParam.setQuery(SolrJUtil.QUERY_ALL);
        queryParam.setStart(start);
        queryParam.setRows(rows);
        PageResult pageResult = searchApi.searchPage(queryParam);
        long total = pageResult.getTotalCount();
        while (CollUtil.isNotEmpty(pageResult.getResult())){
            SolrJUtil.addListMap(pageResult.getResult(), solrCore);
            start += rows;
            queryParam.setStart(start);
            pageResult = searchApi.searchPage(queryParam);
        }
        long end = System.currentTimeMillis();
        String message = module + " 重建索引完成, 耗时:"+((end-begin)/1000)+" 秒，影响 "+total+" 条";
        sysDynamicService.add(new SysDynamicBean(SysConsts.ActionType.UPDATE, "重建索引", message, SessionContextHolder.getUserSessionBean()));
        return message;
    }

}
